<template>
	<view>
		<view class="popup-bg" v-if="popupBg"></view>
		<!-- 导航栏部分 -->
		<view :style="{ height: iStatusBarHeight + 'px'}" class="stat"></view>
		<div class="navigationBar">
			<div class="navigationBarLeft" @click="toIndex()"><i class="uni-btn-icon"></i></div>
			<div class="navigationBarText">亲情相册</div>
		</div>
		<!-- 导航栏部分 -->
		<mescroll-body ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback" :down="downOption"
			:up="upOption">
			<view class="content">
				<view class="albums-box" v-for="(item,index) in album" :key="item.index">
					<!-- <view class="albums-box-title">
						<text>{{item.title}}</text>
					</view> -->
					<view class="in-albums-box">
						<view class="album" @tap="toInfo(item)">
							<view class="image-box">
								<!-- 首次显示，第二次打开页面（也就是读缓存）不显示 -->
								<!-- <view :style="{ 'background-image': 'url(' + smImg(item.imgsrc) + ')' }"></view> -->

								<!-- 缓存正常 -->
								<image :src="item.firstPicture" mode="aspectFill" lazy-load="true"></image>
							</view>
							<view class="album-text">
								<text>{{item.title}}</text>
								<!-- <text>{{item.number}}张</text> -->
							</view>
						</view>
					</view>
				</view>
			</view>
		</mescroll-body>
		<view class="downloader" v-if="downloaderIsShow">
			<h1 style="text-align: center;color: #da422a;">下载视频中...</h1>
			<ProgressBar :Width="downloadStatus" Type="candy" :Main="true" :Vice="true"></ProgressBar>
		</view>
	</view>
</template>

<script>
	import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
	import ProgressBar from '@/components/Progress-Bar/Progress-Bar';
	export default {
		data() {
			return {
				album: [],
				albums: [],
				srccc: [],
				img_src: [],
				img_srcs: [],
				Photo_Num: [],
				// 列表数据
				dataList: [],
				attachIdArr: [],
				upOption: {
					noMoreSize: '', //如果列表已无数据,可设置列表的总数量要大于半页才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看
					empty: {
						use: true,
						icon: '/static/image/zanwushuju@2x.png',
						tip: '~ 无结果 ~', // 提示
					}
				},
				// 下拉刷新的配置(可选, 绝大部分情况无需配置)
				downOption: {
					empty: {
						use: true,
						tip: '~ 无结果 ~' // 提示
					}
				},
				iStatusBarHeight:0, //获取导航栏高度
				videoUrl: '', //视频播放url
				title: '', //视频的标题
				downloadStatus: 0, //视频下载的状态
				downloaderIsShow: false, //控制下载进度条的显示和隐藏
				timer: null, //计时器对象用来生成随机数的
				popupBg: false, // 遮罩层默认不显示
			}
		},
		components: {
			ProgressBar
		},
		mixins: [MescrollMixin], // 使用mixin
		onLoad() {
			this.iStatusBarHeight = uni.getSystemInfoSync().statusBarHeight
			// this.getAlbum()
			// this.upCallback()
		},
		methods: {
			toIndex() {
				uni.switchTab({
					url: '/pages/index/index'
				})
				// console.log('返回首页的点击事件');
			},
			/*下拉刷新的回调, 有3种处理方式:*/
			downCallback() {
				// 绝大部分情况methods中都不用写downCallback的,此时会默认调MescrollMixin的downCallback (效果同第2种)
				this.mescroll.endSuccess()
			},
			/*上拉加载的回调: 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10 */
			async upCallback(page) {

				// 自写
				let pageNum = page.num; // 页码, 默认从1开始
				let pageSize = page.size; // 页长, 默认每页10条
				let cMan = uni.getStorageSync('HC_name')
				console.log(cMan)
				const res = await this
					.$photorequest({ //await 关键字 只能放在 async 函数内部， await关键字的作用 就是获取 Promise中返回的内容， 获取的是Promise函数中resolve或者reject的值
						url: '/api-operate/album/albums?pageSize=' + pageSize + '&pageNumber=' + pageNum +
							'&createdMan=' + cMan,
						method: "get",
					})
				if (res.success == true) {
					// console.log("res", JSON.stringify(res))
					if (res.body.albums.data == null) {
						this.mescroll.endBySize(0, 0);
					} else {
						// 接口返回的当前页数据列表 (数组)
						let curPageData = res.body.albums.data;
						// 接口返回的当前页数据长度 (如列表有26个数据,当前页返回8个,则curPageLen=8)
						let curPageLen = curPageData.length;
						// 接口返回的总页数 (如列表有26个数据,每页10条,共3页; 则totalPage=3)
						let totalPage = res.body.albums.totalPage;
						// 接口返回的总数据量(如列表有26个数据,每页10条,共3页; 则totalSize=26)
						let totalSize = res.body.albums.totalSize;
						// 接口返回的是否有下一页 (true/false)
						let hasNext = false;
						// 请求成功,隐藏加载状态

						this.mescroll.endSuccess()
						this.album = this.album.concat(curPageData); //链接数组
						console.log('album', this.album)

						let album_let = res.body.albums.data
						for (let i in album_let) {
							// console.log(i)
							if (album_let[i].id) {
								// this.getAlbumNum(i)
								const ress = await this
									.$photorequest({ //await 关键字 只能放在 async 函数内部， await关键字的作用 就是获取 Promise中返回的内容， 获取的是Promise函数中resolve或者reject的值
										url: '/api-attach/attachs?pageNumber=1&pageSize=1&onwerId=' + album_let[i]
											.id +
											'&ownerType=com.operate.entity.PhotoAlbum',
										method: "get",
									})


								// console.log(ress.body.list[0])

								album_let[i].number = ress.body.list.length;
								this.attachIdArr[i] = ress.body.list[0]
								let lsattachIdArr = []
								// console.log(this.attachIdArr[i])
								if (this.attachIdArr[i]) {
									// console.log(i)
									album_let[i].imgsrc =
										"http://pm.gxtimeloit.com:10030/api-attach/attachDownload?id=" +
										this.attachIdArr[i].attachId + "&isOnline=1";
									// this.album = album_let
									this.img_srcs[i] =
										"http://pm.gxtimeloit.com:10030/api-attach/attachDownload?id=" +
										this.attachIdArr[i].attachId + "&isOnline=1"
									// console.log(this.attachIdArr[i].attachId)
								}
							}
						}

						this.album = album_let
						// console.log(this.img)
						this.mescroll.endBySize(curPageLen, totalSize);
					}
				}
			},
			// 官方下拉刷新
			onPullDownRefresh() {
				setTimeout(function() {
					uni.stopPullDownRefresh();
				}, 1000);
			},
			smImg(url) {
				// console.log(this.album)
				let real_img = url + '?x-oss-process=image/resize,l_200'
				const cached = uni.getStorageSync(real_img)
				if (cached) {
					console.log(url + "已缓存为：" + cached)
					return cached
				} else {
					// console.log("未缓存,延迟下载")
					setTimeout(() => {
						uni.downloadFile({
							url: url
						}).then(res => {
							if (res[1].statusCode == 200) {
								//#ifdef APP-PLUS
								uni.saveFile({
									tempFilePath: res[1].tempFilePath,
									success: function(res) {
										console.log('下载完成：' + res.savedFilePath);
										uni.setStorageSync(real_img, res
											.savedFilePath)
									}
								});
								//#endif

							} else {
								return Promise.reject('下载临时文件失败')
							}
						}).catch(info => {
							console.log(info);
						})
					}, 2000)
					return real_img
				}

			},
			toInfo(e) {
				// console.log("点击传下来的item", e)
				this.videoUrl = e.imgsrc;
				this.title = e.title;
				// console.log("点击传下来的videoUrl", this.videoUrl)
				if (e.typeText == '视频') {
					this.downloaderIsShow = true;
					this.popupBg = true;
					this.timer = setInterval(this.startTimer, 1000);
					let real_video = this.videoUrl + '?x-oss-process=image/resize,l_200'
					const cached = uni.getStorageSync(real_video)
					if (cached) {
						console.log("已缓存为：" + cached)
						uni.navigateTo({
							url: 'album-video/album-video?title=' + this.title + "&videoUrl=" + cached
						})
						return cached
					} else {
						// console.log("未缓存,延迟下载")
						setTimeout(() => {
							uni.downloadFile({
								url: e.firstPicture
							}).then(res => {
								if (res[1].statusCode == 200) {
									//#ifdef APP-PLUS
									uni.saveFile({
										tempFilePath: res[1].tempFilePath,
										success: function(res) {
											// console.log('下载完成：' + res.savedFilePath);
											// uni.showToast({
											// 	icon: 'success',
											// 	title: '视频下载成功'
											// })
											uni.setStorageSync(real_video, res
												.savedFilePath)
										}
									});
									//#endif

								} else {
									// this.downloadStatus = 99;
									return Promise.reject('下载临时文件失败')
								}
							}).catch(info => {
								console.log(info);
							})
						}, 2000)
						return real_video
					}
				} else {
					uni.navigateTo({
						url: `/pages/familyPhotoAlbum/album-info/album-info?id=` + e.id + `&title=` + e
							.title +
							`&number=` + e.number
					})
				}
			},
			startTimer() {
				// 产生1到5的随机数
				const min = 1;
				const max = 5;
				let randomNum = Math.floor(Math.random() * (max - min + 1)) + min
				// console.log(randomNum);
				this.downloadStatus += randomNum;
				if (this.downloadStatus >= 100) {
					this.downloadStatus = 100;
					uni.showToast({
						icon: 'success',
						title: '下载成功!'
					})
					this.pause()
				}
				// console.log('计时器: ' + this.downloadStatus);
			},
			pause() {
				if (this.timer) {
					clearInterval(this.timer);
					this.downloadStatus = 0;
					this.downloaderIsShow = false;
					this.popupBg = false;
					// console.log('清除计时器');
				}
			},
		},
		onHide() {
			this.pause()
		}
	}
</script>

<style lang="scss" scoped>
	// 导航栏样式
	.stat {
		background-color: #da422a;
		position: fixed;
		z-index: 1;
		height: var(--status-bar-height); // --status-bar-height系统状态栏高度
		width: 100%;
		top: 0;
		left: 0;
	}

	.navigationBar {
		margin-top: var(--status-bar-height);
		background-color: #da422a;
		height: 88rpx;
		display: flex;
		line-height: 88rpx;

		.navigationBarLeft {
			width: 60rpx;
			height: 60rpx;
			margin-left: 1%;

			i {
				color: rgb(255, 255, 255);
				font-size: 27px;
				margin-top: 16rpx;
			}
		}

		.navigationBarText {
			color: aliceblue;
			flex: 1;
			margin-left: 32%;
			font-weight: 700;
			font-size: 32rpx;
		}
	}

	.content {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		padding: 40rpx 0 0 0;
	}

	.albums-box {
		width: 240rpx;
		/* border: 1px solid #F0AD4E; */
		display: flex;
		justify-items: center;
		/* width: 75%; */

	}

	.albums-box-title {
		height: 100rpx;
		position: relative;
		font-size: 44rpx;
		margin-bottom: 30rpx;
	}

	.albums-box-title::after {
		content: "";
		background-color: #E17564;
		width: 100%;
		height: 4rpx;
		position: absolute;
		left: 0;
		right: 0;
		bottom: 0;
	}

	.album {
		margin: 0 auto;

		width: 210rpx;
		height: 320rpx;
		overflow: hidden;

		font-size: 32rpx;

		/* margin-right: 20rpx; */
		display: flex;
		align-items: center;
		flex-direction: column;
		/* border: #007AFF solid 1px; */
	}

	.image-box {
		width: 210rpx;
		height: 210rpx;
		overflow: hidden;
		border-radius: 15rpx;
		display: flex;
		align-items: center;
		flex-direction: column;
		/* border: #007AFF solid 1px; */
		box-shadow: #959595 0rpx 3rpx 3rpx;
	}

	image {
		width: 288rpx;
		height: 280rpx;
	}

	.album-text {
		width: 100%;
		margin-top: 10rpx;
		display: flex;
		justify-content: space-between;
	}

	.in-albums-box {

		width: 100%;
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
	}

	/* 进度条样式 */
	.downloader {
		margin-left: 2%;
		position: absolute;
		top: 30%;
		z-index: 2;
	}

	.popup-bg {
		width: 100%;
		height: 100%;
		position: fixed;
		z-index: 9999;
		top: 0;
		bottom: 0;
		background-color: rgba(1, 1, 1, 0.3);
	}
</style>